package xyz.xtt.asset.mq;

import java.nio.charset.StandardCharsets;
import java.util.Objects;

import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import xyz.xtt.asset.request.EveryDayMessage;
import xyz.xtt.asset.service.ICmpService;

/**
 * @author huqibo
 * @date 2024/12/26
 */
@RefreshScope
@Slf4j
@Component
@RocketMQMessageListener(topic = "${rocketmq.consumer.everydaymsg:QUDAO_SEND_ORDER}", selectorExpression = "${rocketmq.consumer.everytag:QUDAO_SEND_ORDER_1_TAG}", consumerGroup = "${rocketmq.consumer.group.everyday}")
public class EveryDayMessageConsumer implements RocketMQListener<MessageExt> {
	@Autowired
	private ICmpService iCmpService;

	@Value("${rocketmq.consumer.everydaymsg:QUDAO_SEND_ORDER}")
	private String topic;

	@Override
	public void onMessage(MessageExt msg) {
		String msgId = msg.getMsgId();
		log.info("msgId:{}", msgId);
		byte[] body = msg.getBody();
		String message = new String(body, StandardCharsets.UTF_8);
		log.info("onMessage consumerEveryDayMessage topic:{} Received message: {}", topic, msg);
		if (StringUtils.isEmpty(message)) {
			return;
		} else if (!JSONUtil.isTypeJSON(message)) {
			log.error("onMessage consumerEveryDayMessage topic:{} Received message: {} is not json", topic, message);
			return;
		}

		EveryDayMessage everydaymsg = JSONUtil.toBean(message, EveryDayMessage.class);
		if (Objects.isNull(everydaymsg)) {
			log.info("onMessage consumerEveryDayMessage topic:{} JSONUtil.toBean is null", topic);
			return;
		}
		try {
			// 发元素礼包
			Boolean sendEveryDayGriftbox = iCmpService.sendEveryDayGriftbox(everydaymsg);
			log.info("onMessage consumerEveryDayMessage sendEveryDayGriftbox:{}:msg:{} ", sendEveryDayGriftbox, JSONUtil.toJsonStr(everydaymsg));
		} catch (Exception e) {
			log.info("onMessage EveryDayMessageConsumer ex:{}", e.getMessage(), e);
			throw new RuntimeException("onMessage consumerEveryDayMessage Consumer Message exceotion");
		}
	}

}
